package leetcode_1101_1200;

import node.ListNode;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.StreamSupport;

public class LeeCode_1171 {
    public static void main(String[] args) {
        System.out.println(removeZeroSumSublists(new ListNode(1, new ListNode(2, new ListNode(-3, new ListNode(3, new ListNode(1)))))));
        System.out.println(removeZeroSumSublists(new ListNode(1, new ListNode(3,
                new ListNode(2, new ListNode(-3, new ListNode(-2, new ListNode(5, new ListNode(5,
                        new ListNode(-5, new ListNode(1)))))))))));
    }
    private static ListNode removeZeroSumSublists(ListNode head) {
        ListNode dummy = new ListNode(0, head);
        ListNode tmp = dummy;
        int sum = 0;
        Map<Integer, ListNode> map = new HashMap<>();
        while (tmp != null){
            sum += tmp.val;
            if (map.containsKey(sum)){
                ListNode t = map.get(sum).next;
                int ts = sum;
                while (t != tmp){
                    ts += t.val;
                    map.remove(ts);
                    t = t.next;
                }
                tmp = tmp.next;
                map.get(sum).next = tmp;
                continue;
            }
            map.put(sum, tmp);
            tmp = tmp.next;
        }
        return dummy.next;
    }
}